from langchain_openai import ChatOpenAI
from langchain_core.output_parsers import StrOutputParser
import os
from flask import Flask, request, Response, jsonify
from waitress import serve

app = Flask(__name__)
### 解决响应中文乱码问题
app.json.ensure_ascii = False

os.environ['OPENAI_API_KEY'] = 'sk-ioXCJ3W2IQlpDzHu268aEeF7CcAf4b1f9f8c46A248C74a9d'
os.environ['OPENAI_BASE_URL'] = 'https://api.xiaoai.plus/v1'

@app.route('/qaTest', methods=['POST'])
def index1():
    problemData = request.form['problem']
    print("接收客户端传过来的参数：" + problemData)

    ### 输出解析器，将多余消息过滤，只需要回答字符串
    output_parser = StrOutputParser()

    llm = ChatOpenAI()
    llm.model_name = 'gpt-4'

    ###  组合LLM链
    chain = llm | output_parser

    str = chain.invoke(problemData)
    print(str)

    # 返回json
    returnData = {
        "code": 200,
        "msg": "处理成功",
        "data": {
            "answer":str
        }
    }

    return returnData

if __name__ == '__main__':
    serve(app, host='0.0.0.0', port=8526, threads=50)

